package com.sean.community.service;

// import com.sean.community.dao.LoginTicketMapper;
import com.sean.community.dao.UserMapper;
import com.sean.community.entity.LoginTicket;
import com.sean.community.entity.User;
import com.sean.community.util.CommunityConstant;
import com.sean.community.util.CommunityUtil;
import com.sean.community.util.MailClient;
import com.sean.community.util.RedisKeyUtil;
import com.sun.org.apache.xml.internal.utils.res.XResources_ko;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 用户服务层
 */
@Service
public class UserService implements CommunityConstant {
    private UserMapper userMapper;
    private MailClient mailClient;
    private TemplateEngine templateEngine;
    // private LoginTicketMapper loginTicketMapper;
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Autowired
    public void setMailClient(MailClient mailClient) {
        this.mailClient = mailClient;
    }

    @Autowired
    public void setTemplateEngine(TemplateEngine templateEngine) {
        this.templateEngine = templateEngine;
    }

//    @Autowired
//    public void setLoginTicketMapper(LoginTicketMapper loginTicketMapper) {
//        this.loginTicketMapper = loginTicketMapper;
//    }

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 根据 id 查询用户
     * @param id：用户 id
     * @return: User 对象
     */
    public User findUserById(int id){
        // return userMapper.selectById(id);
        User user = this.getCache(id);
        if(user == null){
            user = this.initCache(id);
        }
        return user;
    }

    /**
     * 用户注册
     * @param user： 用户注册信息
     * @return: 哈希表，成功返回空，错误则返回错误信息
     */
    public Map<String, Object> register(User user){
        Map<String, Object> map = new HashMap<>();
        // 过滤空值
        if(user == null){
            throw new IllegalArgumentException("参数不能为空！");
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg", "账号不能为空！");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }
        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }
        // 业务验证
        // 账号是否存在
        User u = userMapper.selectByName(user.getUsername());
        if(u != null){
            map.put("usernameMsg", "该账号已存在！");
            return map;
        }
        // 邮箱验证
        u = userMapper.selectByEmail(user.getEmail());
        if(u != null){
            map.put("emailMsg", "该邮箱已被注册！");
            return map;
        }
        // 开始注册
        // 加盐
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);    // 普通用户
        user.setStatus(0);  // 未激活
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.insertUser(user);
        // 发送激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        // http://127.0.0.1:8080/community/activation/uid/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "账号激活", content);
        return map;
    }

    /**
     * 用户激活
     * @param userId： 用户 id
     * @param code： 用户激活码
     * @return: 激活状态
     */
    public int activation(int userId, String code){
        User user = userMapper.selectById(userId);
        if(user.getStatus() == 1){
            return ACTIVATION_REPEAT;
        }else if(user.getActivationCode().equals(code)){
            userMapper.updateStatus(userId, 1);
            this.clearCache(userId);
            return ACTIVATION_SUCCESS;
        }else{
            return ACTIVATION_FAILURE;
        }
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @param expiredSeconds 登录凭证过期时间
     * @return: 消息映射
     */
    public Map<String, Object> login(String username, String password, int expiredSeconds){
        Map<String, Object> map = new HashMap<>();
        // 空值处理
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg", "账号不能为空！");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }
        // 合法性验证
        User user = userMapper.selectByName(username);
        if(user == null){
            map.put("passwordMsg", "用户名或密码错误！");
            return map;
        }
        if(user.getStatus() == 0){
            map.put("usernameMsg", "该账号未激活！");
            return map;
        }
        String cipherPassword = CommunityUtil.md5(password + user.getSalt());
        if(!user.getPassword().equals(cipherPassword)){
            map.put("passwordMsg", "用户名或密码错误！");
            return map;
        }
        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + (long) expiredSeconds * 1000));
        // loginTicketMapper.insertLoginTicket(loginTicket);       // 将登录凭证存到数据库里效率低 ---改为--> 存到 Redis 中
        // 保存到 redis 中
        String ticketKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(ticketKey, loginTicket);    // 将登录凭证保存到 redis 中，loginTicket 会被序列化为 JSON

        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    /**
     * 退出登录
     * @param ticket 修改 ticket 状态为 1
     */
    public void logout(String ticket){
        // loginTicketMapper.updateStatus(ticket, 1);
        String ticketKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket)redisTemplate.opsForValue().get(ticketKey);
        assert loginTicket != null;
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(ticketKey, loginTicket);
    }

    public LoginTicket findLoginTicket(String ticket){
        // return loginTicketMapper.selectByTicket(ticket);
        String ticketKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket)redisTemplate.opsForValue().get(ticketKey);
    }

    /**
     * 更新用户头像
     * @param userId 用户 id
     * @param headerUrl 用户头像 url
     * @return 影响的行数
     */
    public int updateHeader(int userId, String headerUrl){
        int i = userMapper.updateHeader(userId, headerUrl);
        this.clearCache(userId);
        return i;
    }

    /**
     * 更新用户密码
     * @param userId 用户 id
     * @param oldPassword 用户旧密码
     * @param newPassword 用户新密码
     * @return 影响的行数
     */
    public Map<String, Object> updatePassword(int userId, String oldPassword, String newPassword){
        Map<String, Object> map = new HashMap<>();
        // 空值处理
        if(StringUtils.isBlank(oldPassword)){
            map.put("oldPasswordMsg", "原始密码不能为空！");
            return map;
        }
        if(StringUtils.isBlank(newPassword)){
            map.put("newPasswordMsg", "新密码不能为空！");
            return map;
        }
        // 合法性验证
        User user = userMapper.selectById(userId);
        String cipherPassword = CommunityUtil.md5(oldPassword + user.getSalt());
        if(!user.getPassword().equals(cipherPassword)){
            map.put("oldPasswordMsg", "原始密码错误！");
            return map;
        }
        userMapper.updatePassword(userId, CommunityUtil.md5(newPassword + user.getSalt()));
        this.clearCache(userId);
        return map;
    }

    public User findUserByUsername(String username){
        return userMapper.selectByName(username);
    }

    // 缓存管理
    // 1. 优先从缓存中取值
    private User getCache(int userId){
        String userKey = RedisKeyUtil.getUserKey(userId);
        return (User)redisTemplate.opsForValue().get(userKey);
    }
    // 2. 取不到数据时初始化缓存
    private User initCache(int userId){
        User user = userMapper.selectById(userId);
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(userKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }
    // 3. 当数据发生变化时清除缓存
    private void clearCache(int userId){
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(userKey);
    }

    public Collection<? extends GrantedAuthority> getAuthorities(int userId){
        User user = findUserById(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                if(user.getType() == 0){
                    return AUTHORITY_USER;
                }else if(user.getType() == 1){
                    return AUTHORITY_ADMIN;
                }else if(user.getType() == 2){
                    return AUTHORITY_MODERATOR;
                }
                return null;
            }
        });
        return list;
    }

    /**
     * 获取忘记密码的验证码
     * @param email 邮箱
     * @return 消息集合
     */
    public Map<String, Object> getForgetKaptcha(String email){
        Map<String, Object> map = new HashMap<>();
        // 空值过滤
        if(StringUtils.isBlank(email)){
            map.put("msg", "邮箱不能为空！");
            return map;
        }
        // 合法性校验
        final User user = userMapper.selectByEmail(email);
        if(user == null){
            map.put("msg", "该邮箱账号不存在！");
            return map;
        }
        // 生成验证码
        final String kaptcha = CommunityUtil.generateUUID().substring(0, 6);
        // 发送验证码邮件
        Context context = new Context();
        context.setVariable("email", email);
        context.setVariable("kaptcha", kaptcha);
        String content = templateEngine.process("/mail/forget", context);
        mailClient.sendMail(user.getEmail(), "肖恩论坛-找回密码验证码", content);
        // 保存到 redis 中
        String forgetKaptcha = RedisKeyUtil.getForgetKaptcha(email);
        redisTemplate.opsForValue().set(forgetKaptcha, kaptcha, 300, TimeUnit.SECONDS); // 有效时间 5 分钟
        return map;
    }


    public Map<String, Object> updatePasswordByEmail(String email, String newPassword){
        Map<String, Object> map = new HashMap<>();
        // 空值校验
        if(StringUtils.isBlank(email)){
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }
        if(StringUtils.isBlank(newPassword)){
            map.put("passwordMsg", "新密码不能为空！");
            return map;
        }
        // 合法性校验
        final User user = userMapper.selectByEmail(email);
        if(user == null){
            map.put("emailMsg", "该邮箱未注册！");
            return map;
        }
        userMapper.updatePassword(user.getId(), CommunityUtil.md5(newPassword + user.getSalt()));
        return map;
    }
}
